﻿using System;
using System.IO;
using System.Windows.Input;
using Foundation;
using ICSharpCode.AvalonEdit;
using Microsoft.Win32;

namespace Poet.ViewModels
{
    public class DocumentViewModel : ViewModel
    {
        public DocumentViewModel()
        {
            Title = string.Format("New{0}", ++NewDocumentCounter);
            TextEditor = new TextEditor();
            CommandBindings.Add(new CommandBinding(ApplicationCommands.Close, OnCloseExecute));
            CommandBindings.Add(new CommandBinding(ApplicationCommands.SaveAs, OnSaveAsExecute));
            CommandBindings.Add(new CommandBinding(ApplicationCommands.Save, OnSaveExecute, (o, e) => e.CanExecute = TextEditor.IsModified));
        }

        private void OnSaveAsExecute(object sender, ExecutedRoutedEventArgs e)
        {
            if (_saveFileDialog.ShowDialog() == true)
            {
                DataStream = _saveFileDialog.OpenFile();
                TextEditor.Save(DataStream);
            }
        }

        public void Load(Stream stream)
        {
            DataStream = stream;
            TextEditor.Load(DataStream);
        }

        private void OnSaveExecute(object sender, ExecutedRoutedEventArgs e)
        {
            if (DataStream != null)
            {
                TextEditor.Save(DataStream);
            }
            else
            {
                OnSaveAsExecute(sender, e);
            }
        }

        private void OnCloseExecute(object sender, ExecutedRoutedEventArgs e)
        {
            if (DataStream != null)
            {
                DataStream.Close();
            }

            OnClosed(sender, e);
        }

        public string Title { get; set; }

        public string FullName { get; set; }

        public string ShortName { get; set; }

        public TextEditor TextEditor { get; set; }

        public Stream DataStream { get; set; }

        public EventHandler OnClosed;

        private static int NewDocumentCounter { get; set; }

        private readonly SaveFileDialog _saveFileDialog = new SaveFileDialog();
    }
}
